package ca.ubc.eece310.project;

/**
 * EECE 310 Term Project Fall 2009
 * @author Matthew Fong, Herman Lee, Scott Pearson
 */

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;

public class CommandExecutor {
	/**
	 * OVERVIEW: A class to execute programs from the command line and return
	 * 			 useful information
	 */

	// CONSTRUCTOR
	public CommandExecutor() {
	}

	public ArrayList<RunningProcess> getConnections() {
		/**
		 * EFFECTS: Gets the active processes with ports open and returns a list of them
		 */
		String netstat = new String();
		try {
			String line;
			// execute the netstat command
			java.lang.Process p = Runtime.getRuntime().exec("netstat -o -n");
			// capture the output of netstat
			BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
			while ((line = input.readLine()) != null) {
				netstat = netstat + " \n" + line;
			}
			input.close();
			p.destroy();
		} catch (Exception err) {
			err.printStackTrace();
		}
		/*
		 *	Active Connections 
		 *
		 * 	  Proto  Local Address          Foreign Address        State           PID 
		 * 	  TCP    127.0.0.1:41952        127.0.0.1:50944        ESTABLISHED     3452 
		 *    TCP    127.0.0.1:49159        127.0.0.1:50300        ESTABLISHED     3896 
		 *    TCP    127.0.0.1:50300        127.0.0.1:49159        ESTABLISHED     3732 
		 *    TCP    127.0.0.1:50944        127.0.0.1:41952        ESTABLISHED     23088 
		 *    TCP    127.0.0.1:64066        127.0.0.1:64067        ESTABLISHED     20104 
		 *    TCP    127.0.0.1:64067        127.0.0.1:64066        ESTABLISHED     20104 
		 *    TCP    127.0.0.1:64069        127.0.0.1:64070        ESTABLISHED     20104 
		 */


		int port = 0, PID = 0;
		boolean processExists = false;
		RunningProcess rp;
		ArrayList<RunningProcess> arl = new ArrayList<RunningProcess>();
 
		// parse netstat's output
		netstat = netstat.substring(
				netstat.indexOf("PID") + "PID\n\n".length(), netstat.length()); 
		for (int i = 0; i < netstat.length(); i++) {
			Iterator<RunningProcess> itr = arl.iterator();
			try {
				if (netstat.contains("\n"))
					PID = Integer.parseInt(netstat.substring(netstat
							.lastIndexOf("  ", netstat.indexOf("\n")) + 2,
							netstat.indexOf("\n") - 1));
				else
					PID = Integer.parseInt(netstat.substring(netstat
							.lastIndexOf("  ", netstat.length()) + 2, netstat
							.length()));
				if (PID != 0)
					port = Integer.parseInt(netstat.substring(netstat
							.indexOf(":") + 1, netstat.indexOf(" ", netstat
							.indexOf(":") + 1)));
 
				if (netstat.contains("\n"))
					netstat = netstat.substring(netstat.indexOf("\n") + 1,
							netstat.length());
				else
					netstat = ""; 
				rp = new RunningProcess(PID, new MyPort(port));
				while (itr.hasNext()) {
					if (itr.next().getPID() == PID) {
						processExists = true;
					}
				}
				if (!processExists && PID != 0) {
					arl.add(rp);
				}

				processExists = false;
			} catch (NumberFormatException e) { 
			}
		}
		return arl;
	}

	public String getProcessName(int PID) {
		/**
		 * EFFECTS: Returns the process's name based on its PID
		 * 			If PID does not exist in tasklist, return null
		 */
		String tasklist = new String();
		String processName = new String();
		try {
			String line;
			// execute tasklist filtering by PID
			java.lang.Process p = Runtime.getRuntime().exec("tasklist /FI \"PID eq " + PID + "\"");
			// capture the output
			BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
			while ((line = input.readLine()) != null) {
				tasklist = tasklist + "\n" + line;
			}
			input.close();
			p.destroy();
		} catch (Exception err) {
			err.printStackTrace();
		}

		if (tasklist.equals("INFO: No tasks are running with the specified criteria."))
			return null;

		/* Image Name                     PID Session Name        Session#    Mem Usage
		 * ========================= ======== ================ =========== ============
		 * System Idle Process              0 Services                   0         24 K
		 */

		// parse it
//		System.out.println(tasklist);
		try{
			processName = tasklist.substring(tasklist.lastIndexOf("=") + 2,
			tasklist.indexOf("   ", tasklist.lastIndexOf("=")));
		} catch (StringIndexOutOfBoundsException e) {
			System.out.println(tasklist);
		}
		return processName;
	}

	public static String getHostname() {
		/**
		 * EFFECTS: Returns the computer's hostname
		 */
		String line = new String();
		try {
			// execute hostname
			java.lang.Process p = Runtime.getRuntime().exec("hostname");
			BufferedReader input = new BufferedReader(new InputStreamReader(p
					.getInputStream()));
			line = input.readLine();
			input.close();
			p.destroy();
		} catch (Exception err) {
			err.printStackTrace();
		}
		return line;
	}

}
